package com.pricetag.pricetagandroid;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.pricetag.exceptions.SearchRecordNotExistsException;
import com.pricetag.helpers.Constants;
import com.pricetag.helpers.LocationHolder;
import com.pricetag.helpers.StoreLocations;
import com.pricetag.helpers.Utils;
import com.pricetag.search.SearchHandler;
import com.pricetag.search.SearchRecord;

@SuppressLint("DefaultLocale")
public class LocalStoreSearchResultActivity extends Activity {
	private String searchRecordID;
	private SearchRecord searchRecord;
	private LinearLayout detailContentContainerLayout;
	private Bitmap localImageBitmap;
	private ImageView localImageView;
	private ImageView mapIcon;
	private TextView regularPriceView;
	private TextView salesPriceView;
	private TextView productNameView;
	private LayoutInflater inflater;
	private AtomicBoolean isRunning = new AtomicBoolean(false);
	private Refresher updateListTask;
	private static int currentColor = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		setContentView(R.layout.activity_local_store_search_result);

		Bundle bundle = this.getIntent().getExtras();
		searchRecordID = (String) bundle.get(Constants.SEARCH_RECORD_ID);
		searchRecord = SearchHandler.getSearchRecord(searchRecordID);

		detailContentContainerLayout = (LinearLayout) this
				.findViewById(R.id.detail_content_container_layout);
		detailContentContainerLayout.removeAllViews();
		detailContentContainerLayout.setBackgroundColor(Color.WHITE);
		setupLocalStorePaneLayout();

		ScrollView scrollView = (ScrollView) this
				.findViewById(R.id.search_detail_scroll_view);
		scrollView.smoothScrollTo(0, 0);
		scrollView.setBackgroundColor(Color.WHITE);

		this.isRunning.set(true);

		if (updateListTask != null) {
			updateListTask.cancel(true);
		}

		updateListTask = new Refresher();
		updateListTask.execute(null, null, null);

	}

	@Override
	public void onStop() {
		super.onStop();

		this.isRunning.set(false);

		if (updateListTask != null) {
			updateListTask.cancel(true);
		}
	}

	private void setupLocalStorePaneLayout() {

		LinearLayout categorySelectLayout = new LinearLayout(this);
		categorySelectLayout.setOrientation(LinearLayout.VERTICAL);
		TextView label = new TextView(this);
		label.setTextSize(15);
		label.setText("Specify a category to refine the search");
		categorySelectLayout.addView(label);

		Spinner spinner = new Spinner(this);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.local_store_category,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setSelection(12);
		categorySelectLayout.addView(spinner);

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				String category = parent.getItemAtPosition(pos).toString()
						.toLowerCase().replace(' ', '_');
				if (!category.equals("automatically_detected")) {
					try {
						new SearchHandler(searchRecordID,
								LocalStoreSearchResultActivity.this)
								.searchLocalImageDBWithCategory(category);

					} catch (SearchRecordNotExistsException e) {
						e.printStackTrace();
					}
				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});
		detailContentContainerLayout.addView(categorySelectLayout);

		currentColor = 1;

		final LinearLayout outerLayout = new LinearLayout(this);
		outerLayout.setBackgroundColor(Color.WHITE);
		outerLayout.setOrientation(LinearLayout.HORIZONTAL);
		outerLayout.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, 180, 0f));

		productNameView = this.createFormattedTextView("");
		productNameView.setTextSize(15);
		productNameView.setGravity(Gravity.CENTER);

		outerLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (searchRecord != null
						&& searchRecord.getLocalImageDBSearchResult() != null
						&& searchRecord.getLocalImageDBSearchResult()
								.getMobileUrl() != null) {
					Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(searchRecord.getLocalImageDBSearchResult()
									.getMobileUrl()));
					startActivity(browserIntent);
				}
			}

		});

		detailContentContainerLayout.addView(productNameView);

		this.localImageView = new ImageView(this);
		this.localImageView.setLayoutParams(new LinearLayout.LayoutParams(150,
				180, 0f));

		LinearLayout priceLayout = new LinearLayout(this);
		priceLayout.setOrientation(LinearLayout.VERTICAL);
		priceLayout.setGravity(Gravity.CENTER);
		priceLayout.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.MATCH_PARENT, 0f));

		regularPriceView = this.createFormattedTextView("");
		regularPriceView.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, 45, 0f));
		salesPriceView = this.createFormattedTextView("");
		salesPriceView.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, 45, 0f));

		priceLayout.addView(regularPriceView);
		priceLayout.addView(salesPriceView);
		

		FrameLayout mapAlign = new FrameLayout(this);
		mapAlign.setPadding(0, 32, 0, 0);		
//		mapAlign.setOrientation(LinearLayout.);
//		mapAlign.setGravity(Gravity.BOTTOM);		

		mapIcon = new ImageView(this);		
		mapIcon.setLayoutParams(new LinearLayout.LayoutParams(128, 128, 0f));		
		mapAlign.addView(mapIcon);
		mapIcon.setEnabled(false);		
		mapIcon.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				StoreLocations storeLocations = new StoreLocations();
				ArrayList<LocationHolder> storelocations = storeLocations
						.getStoreDetails();
				Intent intent = new Intent(LocalStoreSearchResultActivity.this,
						MapShowActivity.class);
				intent.putExtra(Constants.LOCATION_STORE, storelocations);
				LocalStoreSearchResultActivity.this.startActivity(intent);
			}

		});

		outerLayout.addView(this.localImageView);
		outerLayout.addView(priceLayout);
		outerLayout.addView(mapAlign);

		TextView textView = new TextView(this);
		textView.setGravity(Gravity.CENTER);
		textView.setText("Click image for details. Click map for local stores.");
		textView.setTextSize(12);
		
		detailContentContainerLayout.addView(outerLayout);
		detailContentContainerLayout.addView(textView);

	}

	private TextView createFormattedTextView(String name) {
		int[] colors = { Color.LTGRAY, Color.WHITE };
		TextView textView = new TextView(this);
		textView.setText(name);
		textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
		textView.setTextSize(12);
		textView.setBackgroundColor(colors[currentColor]);
		currentColor = 1;
		return textView;
	}

	class Refresher extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			if (searchRecord.getLocalImageDBSearchResult() != null
					&& productNameView != null
					&& !productNameView.getText().toString()
							.equals(searchRecord.getLocalImageDBProductName())) {
				localImageBitmap = Utils.getImageBitmap(searchRecord
						.getLocalImageDBSearchResult().getImage());
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void results) {
			if (searchRecord.getLocalImageDBSearchResult() != null
					&& productNameView != null
					&& !productNameView.getText().toString()
							.equals(searchRecord.getLocalImageDBProductName())) {

				localImageView.setImageBitmap(localImageBitmap);
				regularPriceView.setText("Regular CDN$ "
						+ searchRecord.getLocalImageDBSearchResult()
								.getRegularPrice());
				salesPriceView.setText("Sales   CDN$ "
						+ searchRecord.getLocalImageDBSearchResult()
								.getSalePrice());
				productNameView.setText(searchRecord
						.getLocalImageDBProductName().toUpperCase());
				Drawable iconDrawable = getResources().getDrawable(
						R.drawable.map);
				mapIcon.setImageDrawable(iconDrawable);
				mapIcon.setEnabled(true);
			}

			if (isRunning.get()) {
				updateListTask = new Refresher();
				updateListTask.execute(null, null, null);
			}
		}
	}

}
